package com.xukai.springboot.quartzTask;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * Quartz任务管理
 */

@Configuration
public class QuartzTaskManager {


    @Autowired
    private Scheduler scheduler;


    /**
     * 添加任务
     */
    public void AddTask(String taskName, String taskGroupName, Class taskClass, String cron) throws SchedulerException {

        // 任务名，任务组，任务执行类
        JobDetail jobDetail = JobBuilder.newJob(taskClass).withIdentity(taskName, taskGroupName).build();

        // 触发器
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        // 触发器名,触发器组
        triggerBuilder.withIdentity(taskName, taskGroupName);
        triggerBuilder.startNow();
        // 触发器时间设定
        triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
        // 创建Trigger对象
        CronTrigger trigger = (CronTrigger) triggerBuilder.build();

        // 调度容器设置JobDetail和Trigger
        scheduler.scheduleJob(jobDetail, trigger);

        // 启动
        if (!scheduler.isShutdown()) {
            scheduler.start();
        }
    }

    /**
     * 删除任务
     */
    public void RemoveTask(String taskName, String taskGroupName) {
        try {

            TriggerKey triggerKey = TriggerKey.triggerKey(taskName, taskGroupName);

            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(JobKey.jobKey(taskName, taskGroupName));// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改某个任务运行时间
     */
    public void ModifeTask(String taskName, String taskGroupName, String time) throws SchedulerException {

        TriggerKey triggerKey = new TriggerKey(taskName, taskGroupName);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroupName)
                    .withSchedule(cronScheduleBuilder).build();
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }

    /**
     * 获取某个任务信息
     */
    public String GetTaskInfo(String taskName, String taskGroupName) throws SchedulerException {

        TriggerKey triggerKey = new TriggerKey(taskName, taskGroupName);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 判断任务是否存在
     */
    public boolean TaskIsExist(String taskName, String taskGroupName) {
        try {

            TriggerKey triggerKey = new TriggerKey(taskName, taskGroupName);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            return scheduler.checkExists(triggerKey);
        } catch (SchedulerException e) {
            return false;
        }
    }

    /**
     * 暂停某个任务
     */
    public boolean PauseTask(String taskName, String taskGroupName) throws SchedulerException {

        JobKey jobKey = new JobKey(taskName, taskGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return false;
        }
        scheduler.pauseJob(jobKey);
        return true;
    }

    /**
     * 暂停所有任务
     */
    public boolean PauseAllTask() throws SchedulerException {

        if (scheduler.isStarted()) {
            scheduler.shutdown();
        }
        return true;
    }

    /**
     * 恢复所有任务
     */
    public boolean ResumeAllTask() throws SchedulerException {

        scheduler.resumeAll();
        return true;
    }

    /**
     * 恢复某个任务
     */
    public boolean ResumeTask(String taskName, String taskGroupName) throws SchedulerException {

        JobKey jobKey = new JobKey(taskName, taskGroupName);
        Boolean isExist = scheduler.checkExists(jobKey);
        if (!isExist) {
            return false;
        }
        scheduler.resumeJob(jobKey);
        return true;
    }

}
